/*
 * @Author: hongbin
 * @Date: 2021-11-23 17:19:20
 * @LastEditors: hongbin
 * @LastEditTime: 2021-11-26 13:16:03
 * @Description:canvas 画板 支持保存为图片
 */

import {
  FC,
  ReactElement,
  MouseEventHandler,
  useEffect,
  useRef,
  useCallback,
  useMemo,
} from "react";
import styled from "styled-components";
import { flexCenter } from "../components/BUI/styled";
import Panel from "../components/Canvas/Panel";
import { minHeight } from "../components/commentStyled";
import SEO from "../layout/SEO";

interface IProps {}

const Canvas: FC<IProps> = (): ReactElement => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const ctxRef = useRef<CanvasRenderingContext2D>(null);

  useEffect(() => {
    canvasRef.current?.setAttribute(
      "width",
      `${document.body.clientWidth - 100}`
    );
    canvasRef.current?.setAttribute(
      "height",
      `${document.body.clientHeight - 150}`
    );
    // @ts-ignore
    ctxRef.current = canvasRef.current?.getContext("2d");
  }, []);

  const handleMouseDown: MouseEventHandler<HTMLCanvasElement> = () => {
    const canvas = canvasRef.current as HTMLCanvasElement;
    const parentTop = canvas.parentElement!.offsetTop;
    const parentLeft = canvas.parentElement!.offsetLeft;
    const { offsetWidth, offsetTop, offsetLeft } =
      canvasRef.current as HTMLCanvasElement;
    const ctx = ctxRef.current as CanvasRenderingContext2D;

    const move = (e: MouseEvent) => {
      const x = e.pageX - parentLeft - offsetLeft;
      const y = e.pageY - parentTop - offsetTop;
      ctx.beginPath();
      ctx.moveTo(x, y);
      ctx.lineTo(x + 1, y + 1);
      ctx.stroke();
      ctx.closePath();
    };
    canvas.addEventListener("mousemove", move);
    canvas.addEventListener("mouseup", () => {
      canvas.removeEventListener("mousemove", move);
    });
    canvas.addEventListener("mouseleave", () => {
      canvas.removeEventListener("mousemove", move);
    });
  };

  const clearCanvas = useCallback(() => {
    const width = canvasRef.current!.getAttribute("width") as string;
    const height = canvasRef.current!.getAttribute("height") as string;
    ctxRef.current!.clearRect(0, 0, parseFloat(width), parseFloat(height));
  }, []);

  return (
    <Container>
      <SEO title="在线画板" />
      <canvas onMouseDown={handleMouseDown} ref={canvasRef}>
        该浏览器不支持canvas,请移步现代浏览器
      </canvas>
      <Panel clearCanvas={clearCanvas} />
    </Container>
  );
};

export default Canvas;

const Container = styled.div`
  ${minHeight};
  position: relative;
  ${flexCenter};
  overflow: hidden;

  canvas {
    background-color: #fff;
    cursor: pointer;
  }
`;
